import socket
#服务器套接字的端口号
serverPort = 12000 
MaxBytes = 1024
#创建服务器欢迎套接字
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
#绑定端口号与套接字
ss.bind(('', serverPort))
#等待客户敲门
ss.listen()
#while循环将允许UDPServer无限期地接收并处理来自客户的分组
while True:
    print('The server is ready to receive')
    #建立连接套接字
    cns, addr = ss.accept() 
    print('用户已连接')
    filename = ''
    filesize = 0
    while True:
        recvstate = cns.recv(MaxBytes).decode()
        cns.send("\0".encode())
        if recvstate == '0': #是信息
            #开始接收信息
            recvmessage = cns.recv(MaxBytes).decode()
            print('From client: ',recvmessage)
            break
        elif recvstate == '1': #是文件名
            #开始接收文件名
            filename = cns.recv(MaxBytes).decode()
            print('filename:',filename)
            cns.send("\0".encode()) #通知客户文件名已接收
            continue
        elif recvstate == '2': #是文件大小
            #开始接受文件大小
            filesize = int(cns.recv(MaxBytes).decode())
            cns.send("\0".encode()) #通知客户文件大小已接收
            received_size = 0
            f = open(filename,mode = "wb+")
            #接收文件
            while received_size < filesize:
                data = cns.recv(MaxBytes)
                f.write(data)
                received_size += len(data)
            print('文件接收完毕')
            f.close()
            break
    cns.send("已收到".encode())
    cns.close()
